package edu.rpi.tw.escience.stargazer.server;

import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: josh
 * Date: Nov 10, 2008
 * Time: 11:42:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class SimpleException extends Exception {
    private static final Logger LOGGER = Logger.getLogger(SimpleException.class);

    public SimpleException(final String msg) {
        super(msg);
    }
    
    public SimpleException(final Throwable cause) {
        super(cause);
    }

    // Note: copied from RippleException
    public void logError(final boolean includeStackTrace) {
printStackTrace(System.err);
//System.out.println("LOGGING THE ERROR");
        String description;

        if (includeStackTrace) {
            if (null == getCause()) {
                description = getMessage();
            } else {
                try {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    PrintStream ps = new PrintStream(os);
                    getCause().printStackTrace(ps);
                    description = os.toString();
                    ps.close();
                    os.close();
                }

                catch (IOException e) {
                    System.err.println("Failed to create error message. A stack trace of the secondary error follows.");
                    e.printStackTrace(System.err);
                    return;
                }
            }
        } else {
            if (null == getCause()) {
                description = getMessage();
            } else {
                description = getCause().getMessage();
            }
        }

        try {
//System.out.println("REALLY LOGGING THE ERROR");
            LOGGER.error(description);
        }

        catch (Throwable t) {
            System.err.println("Failed to log an exception. A stack trace of the secondary error follows.");
            t.printStackTrace(System.err);
        }
    }

    public void logError() {
        logError(true);
    }
}
